/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.session.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.doll.it.base.constant.Consts;
import org.doll.it.session.bo.DollUserBO;
import org.doll.it.session.util.DollUserUtils;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

/**
 * Session相关事件监听
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
@Slf4j
@WebListener
@Configuration
public class DollSessionListener implements HttpSessionListener, HttpSessionAttributeListener {

	// session创建
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		log.debug("---Session created---, id = " + event.getSession().getId());
		DollUserUtils.setSessionId(event.getSession().getId());
	}

	// session销毁
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		log.debug("---Session Destryed---, id = " + event.getSession().getId());
	}

	// 向session添加属性
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		bingSessionUser(event);
	}

	// 向session移除属性
	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		if (Consts.SESSION_USER_NAME.equals(event.getName())) {
			DollUserUtils.setCurrUser(null);
		}
	}

	// 向session重置属性
	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		bingSessionUser(event);
	}

	/**
	 * 绑定Session用户到全局ThreadLocal
	 * @param event
	 */
	private void bingSessionUser(HttpSessionBindingEvent event) {
		if (Consts.SESSION_USER_NAME.equals(event.getName())) {
			DollUserBO sessionUserVO = (DollUserBO) event.getValue();
			if (sessionUserVO == null) {
				DollUserUtils.setSessionId(event.getSession().getId());
			} else {
				sessionUserVO.setSessionId(event.getSession().getId());
				DollUserUtils.setCurrUser(sessionUserVO);
			}
		}
	}
}
